# coding=UTF-8

from utils import json_util
import decimal


# 获取移动均线
def get_ave_x(x: list, n: int):
    rx = []
    sum_move = 0
    for i in range(len(x)):
        if i < n:
            sum_move += x[i]
            rx.append(round(sum_move / n, 2))
            continue
        sum_move += (x[i] - x[i - n])
        rx.append(round(sum_move / n, 2))
    return rx


# 获取平均线
# 5日均线（MA5）=最近连续5个交易日收盘价之和÷5，即日之前的5日均线数值均会在行情上方显示。
def get_ave_line(code, cal_days, cal_count, klines):
    print("获取平均线,股票编码" + code)
    # print(klines)
    result = {}
    new_klines = []
    sp_list = []
    kl_len = len(klines)
    if kl_len < cal_days + cal_count:
        return result
    for i in range(cal_days + cal_count):
        new_klines.append(klines[kl_len - 1 - i])
    for s_info in new_klines:
        amount = decimal.Decimal(s_info.split(',')[2])
        sp_list.append(amount)
    # 最近连续5个交易日收盘价之和
    sum_amount = 0
    for i in range(cal_count):
        if i == 0:
            for j in range(cal_days):
                sum_amount += sp_list[i + j]
        else:
            sum_amount = (sum_amount - sp_list[i - 1] + sp_list[i + cal_days - 1])
        result[new_klines[i].split(',')[0]] = round(sum_amount / cal_days, 2)
    return result


# 5日均线（MA5）=最近连续5个交易日收盘价之和÷5，即日之前的5日均线数值均会在行情上方显示。
def five_ave_line_price(code, klines):
    # result = {'2020-06-10','62.08'}
    result = get_ave_line(code, 5, 1, klines)
    for key in result:
        return float(result[key])


# n日均线
def ave_line_price_n(code, klines, n):
    # result = {'2020-06-10','62.08'}
    result = get_ave_line(code, n, 1, klines)
    for key in result:
        return float(result[key])


# 传入的均线价格 + 当前实时价格
# klines 包含rt_price当天k
def ave_price_rt(klines, rt_price):
    k_len = len(klines)
    sum = rt_price
    for i in range(1, k_len):
        sum += float(json_util.info_to_json(klines[i])['sp'])
    return round(sum / k_len, 2)


# n日均线价格
def ave_line_price(k_line_dict, n):
    total_price = 0
    for i in range(n):
        total_price += float(json_util.info_to_json(k_line_dict[i])['sp'])
    return round(total_price / n, 2)


# 获取平均线
# local_kline
def local_ave_line(code, days, count, local_kline):
    print("获取平均线,股票编码" + code)
    sum_amount = 0
    dividend = days
    for stock in local_kline:
        if count == 0:
            if days == 0:
                break
            sum_amount += float(eval(str(stock))['sp'])
            days -= 1
        else:
            count -= 1
    return round(sum_amount / dividend, 2)


if __name__ == '__main__':
    print('junxian')
    # get_ave_line('601999', 5, 5, klines)
    print("a")
